package com.dynamic.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.dynamic.datasource.factory.BasicDataSourceFactory;
import com.dynamic.datasource.factory.DataSourceFactory;
import com.dynamic.datasource.factory.DefaultDataSourceFactory;
import com.dynamic.datasource.factory.DruidDataSourceFactory;
import com.dynamic.datasource.factory.HikariDataSourceFactory;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.List;

/**
 * @author 王先堂
 * @Description 数据源创建工厂自动配置
 * @createTime 2022/03/24/ 11:35:00
 */
@Configuration
public class DynamicDataSourceFactoryAutoConfigure {

    /**
     * 注册数据源工厂
     *
     * @param dataSourceFactories 数据源工厂集合
     */
    @Primary
    @Bean
    @ConditionalOnMissingBean
    public DefaultDataSourceFactory dataSourceFactory(List<DataSourceFactory> dataSourceFactories) {
        DefaultDataSourceFactory defaultDataSourceFactory = new DefaultDataSourceFactory();
        defaultDataSourceFactory.setDataSourceFactories(dataSourceFactories);
        return defaultDataSourceFactory;
    }

    @Bean
    public BasicDataSourceFactory basicDataSourceFactory() {
        return new BasicDataSourceFactory();
    }

    /**
     * druid 数据源工厂
     */
    @ConditionalOnClass(DruidDataSource.class)
    @Configuration
    static class DruidDataSourceFactoryConfiguration {
        @Bean
        public DruidDataSourceFactory druidDataSourceFactory() {
            return new DruidDataSourceFactory();
        }
    }

    /**
     * hikari 数据源工厂
     */
    @ConditionalOnClass(HikariDataSource.class)
    @Configuration
    static class HikariDataSourceFactoryConfiguration {
        @Bean
        public HikariDataSourceFactory hikariDataSourceFactory() {
            return new HikariDataSourceFactory();
        }
    }
}
